<template style="background-color: #f6f6f6">

  <el-card class="box-card" >

    <template #header>
      <div class="card-header">
        <span>部门管理</span>
        <span style="float: right;">
            <el-input
                style="float: left;width: 200px;"
                v-model="search"
                size="default"
                placeholder="输入关键字搜索"/>
            <el-select v-model="currentUniId"
                       :disabled="false"
                       style="width: 250px;"
                       @change="initDepartment(true)"
            >
              <el-option
                  v-for="uni in universityList"
                  :key="uni.id"
                  :label="uni.name"
                  :value="uni.id"/>
            </el-select>
            <el-button @click="initUniversity"><el-icon><Refresh /></el-icon></el-button>
          </span>
      </div>
    </template>

    <div style="height: 90%">
      <el-container style="height: 100%">
        <el-aside width="300px" >
          <el-tree
              ref="treeRef"
              :data="treeData"
              node-key="id"
              :props="defaultProps"
              default-expand-all
              @check="handleNodeClick"
              @node-click="handleNodeClick"
              :check-on-click-node="true"
              :highlight-current="true"
              :expand-on-click-node="false"
              show-checkbox
              :check-strictly="true"
          >
            <template #default="{ node, data }">
              <span class="custom-node">
                <span>{{ node.label }}</span>
                <el-button
                    type="text"
                    icon="Plus"
                    @click.stop="addDialogVisible=true;currentParentId=data.id;currentParentName=data.name"
                ></el-button>
              </span>
            </template>

          </el-tree>
        </el-aside>
        <el-main >
          <el-table v-loading="tableLoading"
                    row-key="id"
                    :data="filterData"
                    border stripe >
            <el-table-column prop="workNumber" label="工号" width="150" align="center"/>
            <el-table-column prop="name" label="姓名" width="150" align="center"/>
            <el-table-column prop="department" label="部门" width="200" align="center"/>
            <el-table-column prop="phone" label="电话" align="center"/>
            <el-table-column fixed="right" label="操作" width="270" align="center">
              <template #default="scope">
                <el-button size="small" :type="scope.row.enable===1 ? 'primary':'danger'" @click="disableAccount(scope.row.id,scope.row.enable)">{{ scope.row.enable===1 ? '启用账号':'禁用账号' }}</el-button>
                <el-button size="small" type="primary" @click="resetPassword(scope.row.id)">重置密码</el-button>
                <el-button size="small" type="primary" @click="this.tempInfo=scope.row;this.editDialogVisible=true">编辑信息</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <el-pagination
          :small="true"
          :disabled="false"
          :background="true"
          layout="prev, pager, next"
          @change="initTable"
          v-model:current-page="current"
          :page-count="pageCount"
          style="float: right"
      />
    </div>

  </el-card>

  <el-dialog
      v-model="addDialogVisible"
      title="创建部门"
      width="35%"
      style="text-align: center"
      align-center>

    <el-form :model="form" label-width="100px">
      <el-form-item label="上级部门">
        <el-input v-model="currentParentName" style="width: 450px;" disabled/>
      </el-form-item>
      <el-form-item label="部门名">
        <el-input v-model="form.name" style="width: 450px;" />
      </el-form-item>
      <el-form-item label="简介">
        <el-input
            v-model="form.des"
            style="width: 450px"
            :rows="3"
            type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
              v-loading.fullscreen.lock="addLoading"
              type="primary" @click="addDepartment">
            确认
          </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="editDialogVisible"
      title="编辑信息"
      width="35%"
      style="text-align: center"
      align-center>

    <el-form :model="tempInfo" label-width="100px">
      <el-form-item label="姓名">
        <el-input v-model="tempInfo.name" style="width: 450px;" />
      </el-form-item>
      <el-form-item label="工号">
        <el-input v-model="tempInfo.workNumber" style="width: 450px;" disabled/>
      </el-form-item>
      <el-form-item label="部门">
        <el-cascader
            v-model="tempInfo.deptId"
            ref="cascaderRef"
            :options="treeData"
            :props="tempProps"
            style="width: 450px;"
            @change="console.log(this.$refs.cascaderRef.getCheckedNodes()[0].label)"
        />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="tempInfo.phone" style="width: 450px;" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
              v-loading.fullscreen.lock="editLoading"
              type="primary" @click="editInfo">
            确认
          </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script >
import { ElMessage } from 'element-plus'
import {Edit, Plus, Refresh} from "@element-plus/icons-vue";
export default {
  components: {Plus, Edit, Refresh},
  data(){
    return{
      current:1,
      currentPage:1,
      pageCount:0,
      tableData:[],
      universityList: [],
      currentUniId: '',
      currentDeptIds:[],
      tableLoading:false,
      currentParentId:'',
      currentParentName:'',
      addDialogVisible:false,
      addLoading:false,
      tempInfo:{},
      editDialogVisible:false,
      editLoading:false,
      search:'',
      form:{
        name:'',
        des:''
      },
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tempProps:{
        value: 'id',
        label: 'name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true,
        emitPath:false
      }
    }
  },
  computed:{
    filterData(){
      return this.tableData.filter((data) => {
        return !this.search || data.name!=null&&data.name.toLowerCase().includes(this.search.toLowerCase())||data.id===this.search;
      });
    }
  },
  methods : {
    addDepartment(){
      if(this.form.name.length===0||this.form.des.length===0){
        ElMessage({ message: '请输入完整信息', type: 'warning' });
        return;
      }
      this.addLoading=true;
      console.log(this.currentParentId);
      this.$http.post("/user/department/add",{
        name:this.form.name,
        parentId:this.currentParentId,
        des:this.form.des,
        uniId:this.currentUniId
      }).then((response) => {
        if(response.data.code===200){
          ElMessage({ message: response.data.msg, type: 'success' });
          this.initDepartment(false);
        }
        else {
          ElMessage.error(response.data.msg);
        }
      });
      this.addDialogVisible=false;
      this.addLoading=false;
    },
    handleNodeClick() {
      console.log(this.$refs.treeRef.getCheckedKeys());
      this.currentDeptIds=this.$refs.treeRef.getCheckedKeys();
      if(this.currentDeptIds.length!==0){
        this.initTable();
      }
      else this.tableData=[];
    },
    disableAccount(id,enable){
      let data=new FormData();
      data.append("targetId",id);
      this.$http.put(enable===0?"/user/userManager/user/enable":"/user/userManager/user/disable",data)
          .then((response) => {
            if(response.data.code===200){
              ElMessage({ message: response.data.msg, type: 'success' });
              this.initTable();
            }
            else {
              ElMessage.error(response.data.msg);
            }
          });
    },
    resetPassword(id){
      let data=new FormData();
      data.append("targetId",id);
      this.$http.put("/user/userManager/reset/user/password",data)
        .then((response) => {
          if(response.data.code===200){
            ElMessage({ message: response.data.data, type: 'success' });
          }
          else {
            ElMessage.error(response.data.msg);
          }
        });
    },
    editInfo(){
      if(this.tempInfo.name.length===0||
          this.tempInfo.workNumber.length===0||
          this.tempInfo.deptId.length===0||
          this.tempInfo.department.length===0||
          this.tempInfo.phone.length===0
      ){
        ElMessage({ message: '请输入完整信息', type: 'warning' });
        return;
      }
      this.editLoading=true;
      console.log(this.tempInfo);
      this.$http.put("/user/userManager/edit/teacher",{
        id:this.tempInfo.id,
        name:this.tempInfo.name,
        workNumber:this.tempInfo.workNumber,
        deptId:this.tempInfo.deptId,
        department:this.$refs.cascaderRef.getCheckedNodes()[0].label,
        phone:this.tempInfo.phone
      }).then((response) => {
        if(response.data.code===200){
          ElMessage({ message: response.data.msg, type: 'success' });
          this.initTable();
        }
        else {
          ElMessage.error(response.data.msg);
        }
      });
      this.editDialogVisible=false;
      this.editLoading=false;
    },
    initDepartment(isInit){
      console.log(isInit);
      this.$http.get("/user/department/structure?uniId="+this.currentUniId)
          .then((resp)=>{
        if(resp.data.code===200){
          this.treeData=resp.data.data;
          if(resp.data.data.length===0){
            this.tableData=[];
            return;
          }
          if(isInit) {
            const deptIds=[];
            deptIds.push(resp.data.data[0].id);
            console.log(deptIds)
            this.currentDeptIds = deptIds;
            this.$refs.treeRef.setCheckedKeys(deptIds);
          }
          this.initTable();
        }
      })
    },
    initUniversity(){
      this.tableLoading=true;
      this.$http.get("/user/university/list",{
        page: 1,
        size: 10,
        sortFieId: 'id',
        isASC: 'true'
      }).then((response) => {
        console.log(response);
        if(response.data.code===200){
          this.universityList=response.data.data.records;
          this.currentUniId=response.data.data.records[0].id;
          this.initDepartment(true);
          this.tableLoading=false;
        }
      });
      this.tableLoading=false;
    },
    initTable(){
      this.tableLoading=true;
      this.$http.post("/user/userManager/select/teacher/dept",{
        uniId:this.currentUniId,
        deptIds:this.currentDeptIds,
        page:this.current,
        size:12,
        sortField:'id',
        isASC:'true'
      }).then((response) => {
        console.log(response);
        if(response.data.code===200){
          this.tableData=response.data.data.records;
          this.pageCount=response.data.data.pages;
          this.tableLoading=false;
        }
      });
      this.tableLoading=false;
    }
  },
  mounted(){
    this.initUniversity();
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  height: 94%;
}
.upload_div {
  margin-bottom: 20px;
  width: 114px;
}
.department-tree {
  padding: 20px;
}

.custom-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-tree-node__content {
  height: 36px;
}

.el-tree-node__expand-icon {
  font-size: 16px;
}
.el-main {
  --el-main-padding: 0px;
}
</style>